﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data;
using com.chttl.ienc.bean;

namespace iEN.Immediate
{
    public partial class ShowNowLevel : System.Web.UI.Page
    {
        DataAccess.DBAccess DBAPI = new DataAccess.DBAccess();
        DataAccess.WebService WSAPI = new DataAccess.WebService();

        string strID = "0";

        protected void Page_Load(object sender, EventArgs e)
        {


            if (this.Page.Request.QueryString["ID"] != null)
            {
                strID = this.Page.Request.QueryString["ID"];

                //Create the Row
                //GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                ////Add the two Columns
                //row.Cells.AddRange(CreateCells());
                //gvMain.Parent.Controls.Add(row);

                if (strID == "-1")
                    strID = "0";


                Display();

            }
        }

        private void Display()
        {

            try
            {
                DataTable dtOrg = DBAPI.getOrgGroupTable("1");

                Session["dtOrg"] = dtOrg;

                DataTable dtFloor = dtOrg.Copy();
                DataTable dtBuilding = dtOrg.Copy();

                dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                dtOrg.DefaultView.Sort = " _name";
                dtOrg = dtOrg.DefaultView.ToTable();

                dtFloor.DefaultView.RowFilter = "_id ='" + strID + "'";
                dtFloor = dtFloor.DefaultView.ToTable();

                string strParentID = dtFloor.Rows[0]["_parent_id"].ToString();
                dtBuilding.DefaultView.RowFilter = "_id ='" + strParentID + "'";
                dtBuilding = dtBuilding.DefaultView.ToTable();

                if (dtFloor.Rows.Count > 0)
                    Panel1.GroupingText = dtBuilding.Rows[0]["_name"].ToString() + "/" + dtFloor.Rows[0]["_name"].ToString();

                if (dtOrg.Rows.Count < 1)
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "無任何寢室";
                }

                else
                {
                    lblMsg.Visible = false;
                    Table tbMain = new Table();
                    int iRow = (dtOrg.Rows.Count / 5) + 1;
                    int iMod = dtOrg.Rows.Count % 5;

                    int[] kWHTagIDs = GetkWHTagID(dtOrg);
                    int[] RelayTagIDs = GetRelayTagID(dtOrg);
                    DataObject[] objkWHAry = WSAPI.GetRealtimeTagValue(kWHTagIDs);
                    DataObject[] objRelayAry = WSAPI.GetRealtimeTagValue(RelayTagIDs);

                    for (int i = 1; i <= iRow; i++)
                    {
                        if (i == iRow)
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < iMod; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), objkWHAry, objRelayAry));
                            }
                            tbMain.Rows.Add(tbrM1);

                        }
                        else
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < 5; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), objkWHAry, objRelayAry));
                            }
                            tbMain.Rows.Add(tbrM1);
                        }
                    }
                    Panel1.Controls.Add(tbMain);
                }
            }
            catch
            {

            }

        }

        private TableCell CreateCells(string strID, DataObject[] objkWHAry, DataObject[] objRelayAry)
        {

            DataTable dtOrg = (DataTable)Session["dtOrg"];

            dtOrg.DefaultView.RowFilter = "_id ='" + strID + "'";
            DataTable dtRoom = dtOrg.DefaultView.ToTable();

            //dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
            //DataTable dtFloor = dtOrg.DefaultView.ToTable();

            DataTable dtDevice = DBAPI.getDeviceTable("1");

            int iRoomCnt = 0;
            int iMeter = 0;

            //dtOrg.DefaultView.RowFilter = "_parent_id ='" + dtFloor.Rows[0]["_id"].ToString() + "'";
            //DataTable dtRoom = dtOrg.DefaultView.ToTable();
            //iRoomCnt = dtRoom.Rows.Count;


            //    for (int j = 0; j < dtRoom.Rows.Count; j++)
            //    {
            //        DataTable dtMeter = dtDevice.Copy();
            //        dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[j]["_id"].ToString() + "'";
            //        dtMeter = dtMeter.DefaultView.ToTable();
            //        iMeter = iMeter + dtMeter.Rows.Count;
            //    }
            string strMeterDesc = "";
            DataTable dtMeter = dtDevice.Copy();
            dtMeter.DefaultView.RowFilter = "_org_group_id ='" + strID + "'";
            dtMeter = dtMeter.DefaultView.ToTable();

            TableCell cell = new TableCell();
            Label lbRoom = new Label();
            Label lbMeter = new Label();
            Label lbStatus = new Label();
            System.Web.UI.WebControls.Image imgStatus = new System.Web.UI.WebControls.Image();
            Label lblkWH = new Label();

            if (dtMeter.Rows.Count > 0)
            {

                DataTable dtTag = DBAPI.getTagTable("1");

                DataTable dtTagRelay = dtTag.Copy();

                try
                {
                    dtTag.DefaultView.RowFilter = "_controller_id ='" + dtMeter.Rows[0]["_controller_id"].ToString() + "' and _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "' and _type='1'";
                    dtTag = dtTag.DefaultView.ToTable();
                    int intTagID = 0;
                    if (dtTag.Rows.Count > 0)
                    {
                        intTagID = int.Parse(dtTag.Rows[0]["_id"].ToString());
                    }

                    dtTagRelay.DefaultView.RowFilter = "_controller_id ='" + dtMeter.Rows[0]["_controller_id"].ToString() + "' and _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "' and _name='Relay狀態' and _attribute='AI'";
                    dtTagRelay = dtTagRelay.DefaultView.ToTable();
                    int intRelayTagID = int.Parse(dtTagRelay.Rows[0]["_id"].ToString());


                    strMeterDesc = dtMeter.Rows[0]["_desc"].ToString();

                    lbRoom.Text = dtRoom.Rows[0]["_name"].ToString();

                    lbMeter.Text = "表號 : " + strMeterDesc;

                    lbStatus.Text = "狀態 : ";

                    imgStatus.ImageUrl = "~/images/Green15.gif";
                    imgStatus.Visible = true;

                    lblkWH.Font.Name = "Arial";
                    lblkWH.Font.Size = FontUnit.XLarge;
                    //lblkWH.BackColor = Color.Black;
                    lblkWH.ForeColor = Color.Red;
                    lblkWH.Text = "----.--";
                    //DataObject[] objAry = WSAPI.GetRealtimeTagValue(int.Parse(dtMeter.Rows[0]["_id"].ToString()), "AI");

                    if (objRelayAry == null)
                    {
                        imgStatus.ImageUrl = "~/images/Red15.gif";
                    }

                    string strRelay = "";

                    foreach (TagValue tv in objkWHAry)
                    {
                        int intID = tv.getId();
                        if (intID == intTagID)
                            lblkWH.Text = tv.getValue().ToString("f2");
                    }

                    foreach (TagValue tv in objRelayAry)
                    {
                        int intID = tv.getId();
                        if (intID == intRelayTagID)
                            strRelay = tv.getValue().ToString();
                    }

                    if (strRelay == "")
                    {
                        imgStatus.ImageUrl = "~/images/Red15.gif";
                    }
                    else
                    {
                        if (strRelay == "32768")
                        {
                            imgStatus.ImageUrl = "~/images/Green15.gif";
                        }
                        else
                        {
                            imgStatus.ImageUrl = "~/images/Yellow15.gif";
                        }
                    }
                }
                catch
                {
                    imgStatus.ImageUrl = "~/images/Red15.gif";
                }
                
            }
            else
            {
                lbRoom.Text = dtRoom.Rows[0]["_name"].ToString();
                lbMeter.Text = "此寢室無電錶";
                lbStatus.Text = "狀態 : ";
                imgStatus.Visible = false;
                lblkWH.Font.Name = "Arial";
                lblkWH.Font.Size = FontUnit.XLarge;
                //lblkWH.BackColor = Color.Black;
                lblkWH.ForeColor = Color.Red;
                lblkWH.Text = "----.--";
            }
            

            

            Table tb1 = new Table();
            tb1.Width = 140;

            TableRow tbr1 = new TableRow();
            tbr1.BackColor = Color.LightSkyBlue;
            TableRow tbr2 = new TableRow();
            TableRow tbr3 = new TableRow();
            TableRow tbr4 = new TableRow();

            TableCell tbc1 = new TableCell();
            tbc1.Controls.Add(lbRoom);
            tbc1.HorizontalAlign = HorizontalAlign.Center;
            TableCell tbc2 = new TableCell();
            tbc2.Controls.Add(lbMeter);
            TableCell tbc3 = new TableCell();
            tbc3.Controls.Add(lbStatus);
            tbc3.Controls.Add(imgStatus);
            TableCell tbc4 = new TableCell();
            tbc4.Controls.Add(lblkWH);
            tbc4.BackColor = Color.Black;
            tbc4.HorizontalAlign = HorizontalAlign.Right;

            tbr1.Cells.Add(tbc1);
            tbr2.Cells.Add(tbc2);
            tbr3.Cells.Add(tbc3);
            tbr4.Cells.Add(tbc4);

            tb1.Rows.Add(tbr1);
            tb1.Rows.Add(tbr2);
            tb1.Rows.Add(tbr3);
            tb1.Rows.Add(tbr4);

            tb1.BorderWidth = 2;

            cell.Controls.Add(tb1);

            return cell;
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            Panel1.Controls.Clear();
            Display();
        }


        protected int[] GetkWHTagID(DataTable dtRoom)
        {
            List<int> listTagID = new List<int>();

            DataTable dtDevice = DBAPI.getDeviceTable("1");

            for (int i = 0; i < dtRoom.Rows.Count; i++)
            {
                DataTable dtMeter = dtDevice.Copy();
                dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[i]["_id"].ToString() + "'";
                dtMeter = dtMeter.DefaultView.ToTable();

                if (dtMeter != null && dtMeter.Rows.Count > 0)
                {
                    DataTable dtTag = DBAPI.getTagTable("1");
                    DataTable dtTagTemp = dtTag.Copy();
                    dtTagTemp.DefaultView.RowFilter = " _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "' and _type='1'";
                    dtTagTemp = dtTagTemp.DefaultView.ToTable();

                    if (dtTagTemp != null && dtTagTemp.Rows.Count > 0)
                    {
                        listTagID.Add(int.Parse(dtTagTemp.Rows[0]["_id"].ToString()));

                    }
                }
            }
            int[] TagID = listTagID.ToArray();

            return TagID;
        }

        protected int[] GetRelayTagID(DataTable dtRoom)
        {
            List<int> listTagID = new List<int>();

            DataTable dtDevice = DBAPI.getDeviceTable("1");

            for (int i = 0; i < dtRoom.Rows.Count; i++)
            {
                DataTable dtMeter = dtDevice.Copy();
                dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[i]["_id"].ToString() + "'";
                dtMeter = dtMeter.DefaultView.ToTable();

                if (dtMeter != null && dtMeter.Rows.Count > 0)
                {
                    DataTable dtTag = DBAPI.getTagTable("1");
                    DataTable dtTagTemp = dtTag.Copy();
                    dtTagTemp.DefaultView.RowFilter = " _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "' and _name='Relay狀態' and _attribute='AI'";
                    dtTagTemp = dtTagTemp.DefaultView.ToTable();

                    if (dtTagTemp != null && dtTagTemp.Rows.Count > 0)
                    {
                        listTagID.Add(int.Parse(dtTagTemp.Rows[0]["_id"].ToString()));

                    }
                }
            }
            int[] TagID = listTagID.ToArray();

            return TagID;
        }
    }
}